/**
 * mobx_helper.js
 * MobX辅助工具，提供安全的MobX导入和使用方式
 */

// 尝试导入MobX
let mobx;
try {
  mobx = require('mobx-miniprogram');
} catch (e) {
  console.error('加载mobx-miniprogram失败:', e);
  // 提供最小化兼容实现
  mobx = {
    observable: obj => obj,
    computed: getter => getter,
    action: fn => fn,
    runInAction: fn => fn(),
    configure: () => {},
    autorun: () => ({ dispose: () => {} })
  };
}

// 安全版observable函数
function safeObservable(target) {
  try {
    if (typeof mobx.observable === 'function') {
      return mobx.observable(target);
    } else {
      return target;
    }
  } catch (error) {
    console.error('创建observable失败:', error);
    return target;
  }
}

// 安全版action函数
function safeAction(fn) {
  try {
    if (typeof mobx.action === 'function') {
      return mobx.action(fn);
    } else {
      return fn;
    }
  } catch (error) {
    console.error('创建action失败:', error);
    return fn;
  }
}

// 安全版runInAction函数
function safeRunInAction(fn) {
  try {
    if (typeof mobx.runInAction === 'function') {
      return mobx.runInAction(fn);
    } else {
      return fn();
    }
  } catch (error) {
    console.error('执行runInAction失败:', error);
    return fn();
  }
}

// 安全版computed函数
function safeComputed(fn) {
  try {
    if (typeof mobx.computed === 'function') {
      return mobx.computed(fn);
    } else {
      return fn;
    }
  } catch (error) {
    console.error('创建computed失败:', error);
    return fn;
  }
}

// 使用非装饰器方式创建Store
function createStore(storeDefinition) {
  const store = {};
  
  // 处理状态
  if (storeDefinition.state) {
    Object.assign(store, safeObservable(storeDefinition.state));
  }
  
  // 处理计算属性
  if (storeDefinition.computed) {
    Object.keys(storeDefinition.computed).forEach(key => {
      Object.defineProperty(store, key, {
        get: safeComputed(storeDefinition.computed[key].bind(store)),
        enumerable: true
      });
    });
  }
  
  // 处理action方法
  if (storeDefinition.actions) {
    Object.keys(storeDefinition.actions).forEach(key => {
      store[key] = safeAction(storeDefinition.actions[key].bind(store));
    });
  }
  
  return store;
}

// 尝试加载bindings
let bindings;
try {
  // 优先尝试加载我们的备用实现
  bindings = require('./mobx_bindings');
} catch (e) {
  console.warn('加载mobx_bindings失败，尝试导入原始库:', e);
  
  try {
    bindings = require('mobx-miniprogram-bindings');
  } catch (e2) {
    console.error('加载mobx-miniprogram-bindings失败:', e2);
    // 提供最小化兼容实现
    bindings = {
      createStoreBindings: (context, options) => ({
        destroyStoreBindings: () => {}
      }),
      behavior: () => ({})
    };
  }
}

// 导出所有函数
module.exports = {
  // 原始MobX导出
  mobx,
  
  // 安全包装函数
  observable: safeObservable,
  action: safeAction,
  runInAction: safeRunInAction,
  computed: safeComputed,
  createStore,
  
  // 绑定函数
  createStoreBindings: bindings.createStoreBindings,
  behavior: bindings.behavior
}; 